package project.teg.transfer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.text.TextUtils;

import project.teg.games.game.gestures.Measurement;

public class Transfer {

//	private static String uri = "http://10.0.2.2/GesturesService/WebService1.asmx/HelloWorld";
	private static String uri = "http://192.168.1.7/GesturesService/WebService1.asmx/HelloWorld";

	public static void sendMeasurement(Measurement m) {
		try {
			executeHttpPost(m);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static List<NameValuePair> packData(Measurement m) {

		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		
//				postParameters.add(new BasicNameValuePair("op", "HelloWorld"));
		postParameters.add(new BasicNameValuePair("name", TextUtils
				.htmlEncode(serializeMeasurement(m))));
		return postParameters;
	}

	private static String serializeMeasurement(Measurement m) {
		Serializer serializer = new Persister();
		StringWriter sw = new StringWriter();
		try {
			serializer.write(m, sw);			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sw.toString();
	}

	public static String executeHttpPost(Measurement m) throws Exception {
		BufferedReader in = null;

		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(uri);
		try {
			List<NameValuePair> postParameters = packData(m);

			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParameters);

			request.setEntity(formEntity);

			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String result = sb.toString();
			return result;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
